import api from '../../request/api/login'
export default {
  namespaced: true,
  state: {
    token: '',
    user:  {}
  },
  getters: {
    user(state) {
      return state.user
    },
    // 网格员
    isGridWorker(state, getters) {
      return state.user?.roles?.some?.(i => ['gridWorker'].includes(i.roleKey)) ?? false
    },
    // 普通用户
    isCommon(state, getters) {
      return state.user?.roles?.some?.(i => ['common'].includes(i.roleKey)) ?? false
    },
    // 商户
    isMerchant(state, getters) {
      return state.user?.roles?.some?.(i => ['merchant'].includes(i.roleKey)) ?? false
    },
    // 律师
    isLawyer(state, getters) {
      return state.user?.roles?.some?.(i => ['lawyer'].includes(i.roleKey)) ?? false
    },
    // 夜市管理员
    isNightMarketAdministrator(state, getters) {
      return state.user?.roles?.some?.(i => ['nightMarketAdministrator'].includes(i.roleKey)) ?? false
    },
    // 书记
    isSecretary(state, getters) {
      return state.user?.roles?.some?.(i => ['secretary'].includes(i.roleKey)) ?? false
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, data) => {
      state.user = data
    }
  },

  actions: {
    // 登录
    async Login ({ commit, dispatch }, params) {
      const {token} = await api.login(params)
      commit('SET_TOKEN', `Bearer ${token}`)
      const userInfo = await dispatch('GetInfo')
      commit('SET_USER', userInfo)
    },
    // 微信登录
    async wxLogin ({ commit, dispatch }, otherData = {}) {
      return new Promise((resolve, reject) => {
        uni.login({
          "provider": "weixin",
          success: async ({ code }) => {
            if (code) {
              const { data: { token } } = await api.wxLogin({code, ...otherData})
              if(!token) reject()
              else {
                commit('SET_TOKEN', `Bearer ${token}`)
                const userInfo = await dispatch('GetInfo')
                commit('SET_USER', userInfo)
                resolve(true)
              }
            } else {
              reject()
            }
          },
          fail: (err) => {
            console.log('微信登录失败：', err);
            reject(err)
          }
        })
      })
    },
    // 获取用户信息
    async GetInfo ({ commit, state }) {
      const {user} = await api.getInfo()
      commit('SET_USER', user)
      return user
    },
    // 退出系统
    async userLogOut ({ commit, state }) {
      
    }
  }
}